package cn.edu.huanu.controller;

import cn.edu.huanu.pojo.Book;
import cn.edu.huanu.pojo.Cart;
import cn.edu.huanu.service.BookService;
import cn.edu.huanu.service.impl.BookServiceImpl;
import cn.edu.huanu.utils.JsonUtils;
import cn.edu.huanu.utils.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.util.Objects;

/**
 * @author hb
 * @date 2025-11-19 16:49:18
 */
@WebServlet("*.cart")
public class CartManagerAction extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        String servletPath = req.getServletPath();
        BookService bookService =new BookServiceImpl();

        PrintWriter out = resp.getWriter();

        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        if(Objects.isNull(cart)){
            cart = new Cart();
            session.setAttribute("cart",cart);
        }
        if("/add.cart".equals(servletPath)){
            String idValue = req.getParameter("id");
            Integer id=Integer.parseInt(idValue.trim());
            Book book = bookService.findById(id);
            cart.addItem(book);
            R r=new R();
            System.out.println(JsonUtils.objectToJson(cart));
            r.success().setMessage("添加购物车成功");
            out.println(JsonUtils.objectToJson(r));
        }else if("/load.cart".equals(servletPath)){
            R r=new R();
            if(cart.getItems().size() ==0 ){
                r.error().setMessage("没有任何商品");
            }else{
                cart.setAccount(cart.totalPrice());
                r.success().setData(cart);
            }
            out.println(JsonUtils.objectToJson(r));
        }else if("/addQty.cart".equals(servletPath)){
            String idValue= req.getParameter("id");
            Integer id =Integer.parseInt(idValue.trim());
            String qtyValue =req.getParameter("qty");
            Integer qty = Integer.parseInt(qtyValue.trim());

            cart.updateQty(id,qty);
            cart.setAccount(cart.totalPrice());

            R r=new R();
            r.success().setData(cart);
            out.println(JsonUtils.objectToJson(r));

        }
    }
}
